<?php

namespace app\model;


class Util
{

    static public function createItemPath($type, $ext, $name = '')
    {
        $year = date('Y');
        $day = date('md');

        if ($name) {
            $n = $name . '.' . $ext;
        } else {
            $microtime = microtime(true);
            $milliseconds = round($microtime * 1000);

            $n = $milliseconds . "-" . rand(1000, 9999) . '.' . $ext;
        }

        $save_path = "{$type}/{$year}/{$day}";

        $path = config('app')['public_path'] . '/uploads/' . $save_path;
        self::RecursiveMkdir($path);

        return array(
            'save_path' => $path . '/' . $n,
            'web_path' => $save_path . '/' . $n,
            'cdn_path' => "data/" . $save_path . '/' . $n,
        );
    }

    public static function RecursiveMkdir($path)
    {
        if (!file_exists($path)) {
            self::RecursiveMkdir(dirname($path));
            @mkdir($path, 0777);
        }
    }

    static public function pathToUrl($path, $is_cdn = true)
    {
        if (empty($path)) {
            return false;
        }

        if (strpos($path, 'http') === 0) {
            return $path;
        }
        if ($is_cdn) {
            return config('alicloud')['oss_url'] . '/' . $path;
        } else {
            return config('site')['upload_dir'] . $path;
        }
    }

    static public function deleteFile($path)
    {
        if (file_exists($path)) {
            unlink($path);
        }
    }

    public static function generateCardNumber($length = 12)
    {
        // 去除易混淆字符：0, O, o, I, l, 1
        $characters = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
        $cardNumber = '';
        for ($i = 0; $i < $length; $i++) {
            $cardNumber .= $characters[random_int(0, strlen($characters) - 1)];
        }
        return $cardNumber;
    }

    /**
     * 将折扣百分比（如80%、75.5%）转为中文折扣描述（如8折、7.5折）
     * @param string|float $percent
     * @return string
     */
    public static function percentToDiscountText($percent)
    {
        // 去掉百分号，转为数字
        if (is_string($percent)) {
            $percent = str_replace('%', '', $percent);
        }
        $percent = floatval($percent);

        // 百分比转为折扣
        $discount = $percent / 10;

        // 保留1位小数（如7.5折），如果是整数则不带小数（如8折）
        if (fmod($discount, 1) == 0.0) {
            $discountText = intval($discount) . '折';
        } else {
            $discountText = rtrim(rtrim(number_format($discount, 1, '.', ''), '0'), '.') . '折';
        }
        return $discountText;
    }
}
